<template>
  <el-form ref="formRef" :model="form" label-width="100px" :rules="rules">
    <el-form-item label="资源地址" prop="httpUrl">
      <el-input v-model="form.httpUrl" />
    </el-form-item>
    <el-form-item label="请求方法" prop="httpMethod">
      <el-select
        v-model="form.httpMethod"
        placeholder="请选择请求方法"
        style="width: 240px"
      >
        <el-option
          v-for="item in methodOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="Header">
      <el-table :data="httpHeader" border style="width: 100%">
        <el-table-column label="序号" width="80" align="center">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>

        <el-table-column label="参数名称" prop="name" width="180">
          <template #default="{ row }">
            <el-input v-model="row.paramName" placeholder="请输入参数名称" />
          </template>
        </el-table-column>

        <el-table-column label="参数类型" prop="type" width="120">
          <template #default="{ row }">
            <el-select
              v-model="row.paramType"
              placeholder="请选择参数类型"
              style="width: 100%"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="参数描述" prop="description">
          <template #default="{ row }">
            <el-input
              v-model="row.paramDes"
              type="textarea"
              :rows="1"
              placeholder="请输入参数描述"
            />
          </template>
        </el-table-column>

        <el-table-column label="输入值" prop="value" width="200">
          <template #default="{ row }">
            <el-input
              v-model="row.paramValue"
              :type="row.paramType"
              placeholder="请输入值"
            />
          </template>
        </el-table-column>

        <el-table-column
          v-if="!props.docId"
          label="操作"
          width="100"
          align="center"
        >
          <template #default="{ $index }">
            <el-button
              type="danger"
              size="small"
              @click="deleteRow(httpHeader, $index)"
              :icon="Delete"
              circle
            />
          </template>
        </el-table-column>
      </el-table>
      <el-button
        style="width: 100%"
        v-show="!props.docId"
        @click="addNewRow(httpHeader)"
        class="mt-4"
      >
        <el-icon><plus /></el-icon>添加行
      </el-button>
    </el-form-item>
    <el-form-item label="请求参数">
      <el-table :data="httpReq" border style="width: 100%">
        <el-table-column label="序号" width="80" align="center">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>

        <el-table-column label="参数名称" prop="name" width="180">
          <template #default="{ row }">
            <el-input v-model="row.paramName" placeholder="请输入参数名称" />
          </template>
        </el-table-column>

        <el-table-column label="参数类型" prop="type" width="120">
          <template #default="{ row }">
            <el-select
              v-model="row.paramType"
              placeholder="请选择参数类型"
              style="width: 100%"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column label="参数描述" prop="description">
          <template #default="{ row }">
            <el-input
              v-model="row.paramDes"
              type="textarea"
              :rows="1"
              placeholder="请输入参数描述"
            />
          </template>
        </el-table-column>

        <el-table-column label="输入值" prop="value" width="200">
          <template #default="{ row }">
            <el-input v-model="row.paramValue" placeholder="请输入值" />
          </template>
        </el-table-column>

        <el-table-column
          v-if="!props.docId"
          label="操作"
          width="100"
          align="center"
        >
          <template #default="{ $index }">
            <el-button
              type="danger"
              size="small"
              @click="deleteRow(httpReq, $index)"
              :icon="Delete"
              circle
            />
          </template>
        </el-table-column>
      </el-table>
      <el-button
        v-show="!props.docId"
        style="width: 100%"
        @click="addNewRow(httpReq)"
        class="mt-4"
      >
        <el-icon><plus /></el-icon>添加行
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  resourceinfo,
  resourceinfosave,
  resourceinfoSaveDynamic,
  resourceinfoGeneralSaveDynamic,
  resourceinfoDynamic,
  resourceinfoDynamicDoc,
} from "@/api/naturalRes";
import { Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

// saveDynamicForm 定义
interface saveDynamicForm {
  resId?: string;
  httpUrl?: string;
  httpMethod?: string;
  httpReq?: string | string[];
  httpHeader?: string | string[];
}

// Props 定义
interface Props {
  modelValue?: string;
  disabled?: boolean;
  id?: string;
  docId?: string;
  plugins?: string | string[];
  toolbar?: string | string[];
  data?: any;
  documentId: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: "",
  disabled: false,
  id: "111",
  docId: null,
  plugins: "advlist autolink lists link image table wordcount",
  toolbar:
    "undo redo | formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media table | removeformat",
  data: {},
  documentId: "",
});

// Emits 定义
const emit = defineEmits<{
  (e: "onClick", event: any): void;
  (e: "update:id", value: any): void;
}>();

const router = useRouter();
const route = useRoute();
const id = ref(route.params.id);
const editorId = ref(props.id);
const formRef = ref(null);
const form: saveDynamicForm = reactive({});
const fristcreate = ref(true);

const rules = reactive({
  httpUrl: [{ required: true, message: "请输入资源地址", trigger: "blur" }],
});

// 参数类型选项
const typeOptions = [
  { value: "1101", label: "字符串" },
  { value: "1102", label: "日期" },
  { value: "1103", label: "数字" },
  { value: "boolean", label: "布尔值" },
  { value: "array", label: "数组" },
  { value: "object", label: "对象" },
];

const methodOptions = [
  { value: "POST", label: "POST" },
  { value: "GET", label: "GET" },
];

// 资源请求参数（Json）
const httpReq = ref([
  {
    paramName: "",
    paramType: "",
    paramDes: "",
    paramValue: "",
  },
]);

// 资源请求头参数
const httpHeader = ref([
  {
    paramName: "",
    paramType: "",
    paramDes: "",
    paramValue: "",
  },
]);

// 如果是编辑，加载用户数据
onMounted(() => {
  if (id.value && id.value !== "0" && id.value != "add") {
    // loadUserData();
  }
  init();
});

const init = async () => {
  console.log("props.id", props.id,props.docId);
  if (props.id && props.id != "add" && !props.docId) {
    const data: any = await resourceinfoDynamic(props.id);
    console.log("data", data);

    httpHeader.value = data.httpHeader ? data.httpHeader : [];
    httpReq.value = data.httpReq ? data.httpReq : [];
    form.httpMethod = data.httpMethod;
    form.httpUrl = data.httpUrl;
  } else if (props.docId) {
    const data: any = await resourceinfoDynamicDoc(props.id, props.docId);
    httpHeader.value = data.httpHeader;
    httpReq.value = data.httpReq;
    form.httpMethod = data.httpMethod;
    form.httpUrl = data.httpUrl;
  }
};
// 加载用户数据
const loadUserData = async () => {
  // 这里应该是API请求，我们模拟一下
  const mockData = await resourceinfo(id.value as string);
  console.log("mockData", mockData);
  Object.assign(form, mockData);
};

// 添加新行
const addNewRow = (tableData) => {
  console.log("tableData", tableData);

  tableData.push({
    name: "",
    type: "",
    description: "",
    value: "",
  });
};

// 删除行
const deleteRow = (tableData, index) => {
  // if (tableData.length > 1) {
  tableData.splice(index, 1);
  // } else {
  //   ElMessage.warning("至少保留一行数据");
  // }
};

//是否是新增
const isNatAdd = async () => {
  if (route.params.id == "add") {
    if (Object.keys(props.data).length === 0) {
      ElMessage.error("请先填写资源类型信息");
    } else {
      const data: any = await resourceinfosave(props.data);
      editorId.value = data;
    }
  }
};

// 保存数据
const saveData = async () => {
  if (route.params.id == "add" && fristcreate.value) {
    if (Object.keys(props.data).length === 0) {
      ElMessage.error("请先填写资源类型信息");
    } else {
      const data: any = await resourceinfosave(props.data);
      fristcreate.value = false;
      editorId.value = data;
      emit("update:id", data);
    }
  }
  if (httpReq.value.length > 0) {
    for (let i = httpReq.value.length - 1; i >= 0; i--) {
      if (httpReq.value[i].paramName == null || httpReq.value[i].paramName == "") {
        httpReq.value.splice(i, 1);
      }
    }
  }
  if (httpHeader.value.length > 0) {
    for (let i = httpHeader.value.length - 1; i >= 0; i--) {
      console.log('httpHeader.value[i]',httpHeader.value[i]);
      if (httpHeader.value[i].paramName == null || httpReq.value[i].paramName == "") {
        httpHeader.value.splice(i, 1);
      }
    }
  }
  const saveDynamicData = {
    resId: editorId.value,
    httpUrl: form.httpUrl,
    httpMethod: form.httpMethod,
    httpReq: httpReq.value,
    httpHeader: httpHeader.value,
  };
  if (props.docId) {
    await resourceinfoSaveDynamic(saveDynamicData, props.docId);
  } else {
    await resourceinfoGeneralSaveDynamic(saveDynamicData);
  }
};

// 重置数据
const resetData = (tableData) => {
  tableData = [
    {
      name: "",
      type: "",
      description: "",
      value: "",
    },
  ];
  ElMessage.success("已重置表格");
};

defineExpose({
  saveData,
  isNatAdd,
});
</script>

<style scoped>
.user-edit-container {
  padding: 20px;
}

/* .editable-table-container {
  padding: 20px;
} */

.add-btn {
  margin-bottom: 15px;
}

.footer {
  margin-top: 15px;
  text-align: right;
}

.el-input,
.el-textarea {
  width: 100%;
}

:deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 32px;
}
</style>
